import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Textarea } from '../ui/textarea';
import { Input } from '../ui/input';
import { 
  Calendar, 
  Clock, 
  Users, 
  CheckCircle, 
  XCircle,
  AlertCircle,
  FileText,
  Save,
  Download,
  BarChart3
} from 'lucide-react';

interface Student {
  id: string;
  studentId: string;
  name: string;
  attendanceStatus: 'present' | 'absent' | 'late' | 'leave' | '';
}

interface AttendanceRecord {
  id: string;
  date: string;
  courseName: string;
  className: string;
  totalStudents: number;
  presentCount: number;
  absentCount: number;
  lateCount: number;
  leaveCount: number;
}

interface LeaveRequest {
  id: string;
  studentId: string;
  studentName: string;
  courseName: string;
  leaveType: string;
  startDate: string;
  endDate: string;
  reason: string;
  status: 'pending' | 'approved' | 'rejected';
  submitDate: string;
}

export function AttendanceManagement() {
  const [selectedCourse, setSelectedCourse] = useState('math001-computer21-1');
  const [selectedDate, setSelectedDate] = useState('2024-03-20');
  const [attendanceNote, setAttendanceNote] = useState('');

  const students: Student[] = [
    { id: '1', studentId: '2021001001', name: '张三', attendanceStatus: 'present' },
    { id: '2', studentId: '2021001002', name: '李四', attendanceStatus: 'present' },
    { id: '3', studentId: '2021001003', name: '王五', attendanceStatus: 'late' },
    { id: '4', studentId: '2021001004', name: '赵六', attendanceStatus: 'leave' },
    { id: '5', studentId: '2021001005', name: '钱七', attendanceStatus: 'absent' },
    { id: '6', studentId: '2021001006', name: '孙八', attendanceStatus: 'present' },
    { id: '7', studentId: '2021001007', name: '周九', attendanceStatus: 'present' },
    { id: '8', studentId: '2021001008', name: '吴十', attendanceStatus: 'present' }
  ];

  const attendanceRecords: AttendanceRecord[] = [
    {
      id: '1',
      date: '2024-03-18',
      courseName: '高等数学A',
      className: '计算机21-1班',
      totalStudents: 42,
      presentCount: 39,
      absentCount: 1,
      lateCount: 2,
      leaveCount: 0
    },
    {
      id: '2',
      date: '2024-03-15',
      courseName: '高等数学A',
      className: '计算机21-1班',
      totalStudents: 42,
      presentCount: 40,
      absentCount: 0,
      lateCount: 1,
      leaveCount: 1
    },
    {
      id: '3',
      date: '2024-03-13',
      courseName: '高等数学A',
      className: '计算机21-2班',
      totalStudents: 38,
      presentCount: 36,
      absentCount: 2,
      lateCount: 0,
      leaveCount: 0
    }
  ];

  const leaveRequests: LeaveRequest[] = [
    {
      id: '1',
      studentId: '2021001004',
      studentName: '赵六',
      courseName: '高等数学A',
      leaveType: '病假',
      startDate: '2024-03-20',
      endDate: '2024-03-20',
      reason: '感冒发烧，需要休息治疗',
      status: 'pending',
      submitDate: '2024-03-19'
    },
    {
      id: '2',
      studentId: '2021001012',
      studentName: '李明',
      courseName: '高等数学A',
      leaveType: '事假',
      startDate: '2024-03-22',
      endDate: '2024-03-23',
      reason: '家中有事需要回家处理',
      status: 'pending',
      submitDate: '2024-03-20'
    }
  ];

  const getAttendanceStatusBadge = (status: string) => {
    switch (status) {
      case 'present':
        return <Badge className="bg-green-100 text-green-800"><CheckCircle className="w-3 h-3 mr-1" />出勤</Badge>;
      case 'absent':
        return <Badge variant="destructive"><XCircle className="w-3 h-3 mr-1" />旷课</Badge>;
      case 'late':
        return <Badge variant="outline"><Clock className="w-3 h-3 mr-1" />迟到</Badge>;
      case 'leave':
        return <Badge variant="secondary"><FileText className="w-3 h-3 mr-1" />请假</Badge>;
      default:
        return <Badge variant="outline">未记录</Badge>;
    }
  };

  const getLeaveStatusBadge = (status: string) => {
    switch (status) {
      case 'approved':
        return <Badge className="bg-green-100 text-green-800">已批准</Badge>;
      case 'rejected':
        return <Badge variant="destructive">已驳回</Badge>;
      case 'pending':
        return <Badge variant="outline">待审批</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  const updateAttendanceStatus = (studentId: string, status: string) => {
    // In a real app, this would update the state
    console.log(`Updating student ${studentId} to ${status}`);
  };

  const getAttendanceStats = () => {
    const present = students.filter(s => s.attendanceStatus === 'present').length;
    const absent = students.filter(s => s.attendanceStatus === 'absent').length;
    const late = students.filter(s => s.attendanceStatus === 'late').length;
    const leave = students.filter(s => s.attendanceStatus === 'leave').length;
    const total = students.length;
    const attendanceRate = total > 0 ? ((present / total) * 100).toFixed(1) : '0';

    return { present, absent, late, leave, total, attendanceRate };
  };

  const stats = getAttendanceStats();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">考勤管理</h1>
        <div className="flex gap-2">
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            导出考勤表
          </Button>
        </div>
      </div>

      <Tabs defaultValue="register" className="space-y-4">
        <TabsList>
          <TabsTrigger value="register">考勤登记</TabsTrigger>
          <TabsTrigger value="statistics">考勤统计</TabsTrigger>
          <TabsTrigger value="leave">请假审批</TabsTrigger>
        </TabsList>

        <TabsContent value="register" className="space-y-4">
          {/* Course and Date Selection */}
          <Card>
            <CardContent className="p-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex gap-2 items-center">
                  <label className="text-sm font-medium">选择课程:</label>
                  <Select value={selectedCourse} onValueChange={setSelectedCourse}>
                    <SelectTrigger className="flex-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="math001-computer21-1">高等数学A - 计算机21-1班</SelectItem>
                      <SelectItem value="math001-computer21-2">高等数学A - 计算机21-2班</SelectItem>
                      <SelectItem value="math002-math21-1">线性代数 - 数学21-1班</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <div className="flex gap-2 items-center">
                  <label className="text-sm font-medium">上课日期:</label>
                  <Input
                    type="date"
                    value={selectedDate}
                    onChange={(e) => setSelectedDate(e.target.value)}
                    className="flex-1"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Attendance Stats */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <Card>
              <CardContent className="p-4 text-center">
                <Users className="h-6 w-6 mx-auto mb-2 text-blue-500" />
                <p className="text-sm text-muted-foreground">总人数</p>
                <p className="text-xl font-medium">{stats.total}</p>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-4 text-center">
                <CheckCircle className="h-6 w-6 mx-auto mb-2 text-green-500" />
                <p className="text-sm text-muted-foreground">出勤</p>
                <p className="text-xl font-medium text-green-600">{stats.present}</p>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-4 text-center">
                <XCircle className="h-6 w-6 mx-auto mb-2 text-red-500" />
                <p className="text-sm text-muted-foreground">旷课</p>
                <p className="text-xl font-medium text-red-600">{stats.absent}</p>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-4 text-center">
                <Clock className="h-6 w-6 mx-auto mb-2 text-orange-500" />
                <p className="text-sm text-muted-foreground">迟到</p>
                <p className="text-xl font-medium text-orange-600">{stats.late}</p>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-4 text-center">
                <FileText className="h-6 w-6 mx-auto mb-2 text-purple-500" />
                <p className="text-sm text-muted-foreground">请假</p>
                <p className="text-xl font-medium text-purple-600">{stats.leave}</p>
              </CardContent>
            </Card>
          </div>

          {/* Attendance Registration Table */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                考勤登记 - 高等数学A (计算机21-1班) - {selectedDate}
                <div className="flex gap-2">
                  <Button variant="outline" size="sm">全部出勤</Button>
                  <Button size="sm">
                    <Save className="mr-2 h-4 w-4" />
                    保存考勤
                  </Button>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>学号</TableHead>
                    <TableHead>姓名</TableHead>
                    <TableHead>考勤状态</TableHead>
                    <TableHead>快速操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {students.map((student) => (
                    <TableRow key={student.id}>
                      <TableCell className="font-medium">{student.studentId}</TableCell>
                      <TableCell>{student.name}</TableCell>
                      <TableCell>
                        <Select 
                          value={student.attendanceStatus} 
                          onValueChange={(value) => updateAttendanceStatus(student.id, value)}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="present">出勤</SelectItem>
                            <SelectItem value="absent">旷课</SelectItem>
                            <SelectItem value="late">迟到</SelectItem>
                            <SelectItem value="leave">请假</SelectItem>
                          </SelectContent>
                        </Select>
                      </TableCell>
                      <TableCell>
                        <div className="flex space-x-1">
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => updateAttendanceStatus(student.id, 'present')}
                          >
                            <CheckCircle className="h-3 w-3 text-green-500" />
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => updateAttendanceStatus(student.id, 'absent')}
                          >
                            <XCircle className="h-3 w-3 text-red-500" />
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => updateAttendanceStatus(student.id, 'late')}
                          >
                            <Clock className="h-3 w-3 text-orange-500" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              <div className="mt-4 space-y-2">
                <label className="text-sm font-medium">考勤备注</label>
                <Textarea
                  placeholder="请输入本次课程的考勤备注..."
                  value={attendanceNote}
                  onChange={(e) => setAttendanceNote(e.target.value)}
                  rows={2}
                />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="statistics" className="space-y-4">
          {/* Attendance Overview */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <BarChart3 className="mr-2 h-5 w-5" />
                考勤统计概览
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>日期</TableHead>
                    <TableHead>课程</TableHead>
                    <TableHead>班级</TableHead>
                    <TableHead>总人数</TableHead>
                    <TableHead>出勤</TableHead>
                    <TableHead>旷课</TableHead>
                    <TableHead>迟到</TableHead>
                    <TableHead>请假</TableHead>
                    <TableHead>出勤率</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {attendanceRecords.map((record) => (
                    <TableRow key={record.id}>
                      <TableCell>{record.date}</TableCell>
                      <TableCell>{record.courseName}</TableCell>
                      <TableCell>{record.className}</TableCell>
                      <TableCell>{record.totalStudents}</TableCell>
                      <TableCell className="text-green-600">{record.presentCount}</TableCell>
                      <TableCell className="text-red-600">{record.absentCount}</TableCell>
                      <TableCell className="text-orange-600">{record.lateCount}</TableCell>
                      <TableCell className="text-purple-600">{record.leaveCount}</TableCell>
                      <TableCell className="font-medium">
                        {((record.presentCount / record.totalStudents) * 100).toFixed(1)}%
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          {/* Class Performance Comparison */}
          <Card>
            <CardHeader>
              <CardTitle>班级考勤对比</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="p-4 border rounded-lg">
                  <h4 className="font-medium mb-3">计算机21-1班</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>平均出勤率</span>
                      <span className="text-green-600 font-medium">95.2%</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>迟到次数</span>
                      <span className="text-orange-600">8次</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>旷课次数</span>
                      <span className="text-red-600">3次</span>
                    </div>
                  </div>
                </div>
                
                <div className="p-4 border rounded-lg">
                  <h4 className="font-medium mb-3">计算机21-2班</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>平均出勤率</span>
                      <span className="text-green-600 font-medium">92.1%</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>迟到次数</span>
                      <span className="text-orange-600">12次</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>旷课次数</span>
                      <span className="text-red-600">6次</span>
                    </div>
                  </div>
                </div>
                
                <div className="p-4 border rounded-lg">
                  <h4 className="font-medium mb-3">数学21-1班</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>平均出勤率</span>
                      <span className="text-green-600 font-medium">98.5%</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>迟到次数</span>
                      <span className="text-orange-600">3次</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>旷课次数</span>
                      <span className="text-red-600">1次</span>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="leave" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <AlertCircle className="mr-2 h-5 w-5" />
                待审批请假申请
              </CardTitle>
            </CardHeader>
            <CardContent>
              {leaveRequests.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <AlertCircle className="mx-auto h-12 w-12 mb-4" />
                  <p>暂无待处理的请假申请</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {leaveRequests.map((request) => (
                    <Card key={request.id} className="border-l-4 border-l-orange-500">
                      <CardContent className="p-4">
                        <div className="flex justify-between items-start mb-3">
                          <div>
                            <h4 className="font-medium">{request.studentName} ({request.studentId})</h4>
                            <p className="text-sm text-muted-foreground">{request.courseName}</p>
                          </div>
                          <div className="text-right">
                            <Badge variant="outline">{request.leaveType}</Badge>
                            <p className="text-sm text-muted-foreground mt-1">申请时间: {request.submitDate}</p>
                          </div>
                        </div>
                        
                        <div className="mb-3">
                          <p className="text-sm"><strong>请假时间:</strong> {request.startDate} {request.startDate !== request.endDate && `至 ${request.endDate}`}</p>
                          <p className="text-sm"><strong>请假原因:</strong> {request.reason}</p>
                        </div>
                        
                        <div className="flex gap-2">
                          <Button size="sm" className="bg-green-600 hover:bg-green-700">
                            <CheckCircle className="mr-1 h-3 w-3" />
                            批准
                          </Button>
                          <Button variant="outline" size="sm">
                            <XCircle className="mr-1 h-3 w-3" />
                            驳回
                          </Button>
                          <Button variant="ghost" size="sm">
                            查看详情
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}